<template>
  <view class="quicktest-container">
    <!-- 统计卡片 -->
    <view class="stat-cards">
      <view class="stat-card">
        <view class="stat-icon blue">
          <uni-icons type="calendar" size="24" color="#1890ff"></uni-icons>
        </view>
        <view class="stat-info">
          <view class="stat-value">{{ statistics.today }}</view>
          <view class="stat-label">今日检测</view>
        </view>
      </view>
      <view class="stat-card">
        <view class="stat-icon green">
          <uni-icons type="checkbox-filled" size="24" color="#52c41a"></uni-icons>
        </view>
        <view class="stat-info">
          <view class="stat-value">{{ statistics.passed }}</view>
          <view class="stat-label">合格数</view>
        </view>
      </view>
      <view class="stat-card">
        <view class="stat-icon red">
          <uni-icons type="closeempty" size="24" color="#ff4d4f"></uni-icons>
        </view>
        <view class="stat-info">
          <view class="stat-value">{{ statistics.failed }}</view>
          <view class="stat-label">不合格数</view>
        </view>
      </view>
    </view>

    <!-- 待检测列表 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">待检测列表</text>
        <view class="filter-tabs">
          <view 
            :class="['tab-item', currentTab === '0' ? 'active' : '']"
            @click="switchTab('0')"
          >
            待检测
          </view>
          <view 
            :class="['tab-item', currentTab === '1' ? 'active' : '']"
            @click="switchTab('1')"
          >
            已完成
          </view>
        </view>
      </view>

      <scroll-view 
        scroll-y 
        class="list-container"
        @scrolltolower="loadMore"
        :refresher-enabled="true"
        :refresher-triggered="refreshing"
        @refresherrefresh="onRefresh"
      >
        <view v-if="list.length > 0">
          <view v-for="item in list" :key="item.detailId" class="test-item" @click="showTestDialog(item)">
            <view class="item-header">
              <view class="item-info">
                <view class="goods-name">{{ item.goodsName }}</view>
                <view class="merchant-info">
                  <text class="label">商户：</text>
                  <text class="value">{{ item.merchantName }}</text>
                </view>
              </view>
              <view v-if="item.inspectionStatus === '0'" class="status-badge pending">
                待检测
              </view>
              <view v-else-if="item.inspectionStatus === '1'" class="status-badge passed">
                合格
              </view>
              <view v-else-if="item.inspectionStatus === '2'" class="status-badge failed">
                不合格
              </view>
            </view>
            
            <view class="item-content">
              <view class="info-row">
                <view class="info-item">
                  <text class="label">预约编号：</text>
                  <text class="value">{{ item.applyNo }}</text>
                </view>
                <view class="info-item">
                  <text class="label">数量：</text>
                  <text class="value">{{ item.quantity }}{{ item.unit }}</text>
                </view>
              </view>
              <view class="info-row">
                <view class="info-item">
                  <text class="label">供货商：</text>
                  <text class="value">{{ item.supplierName }}</text>
                </view>
              </view>
              <view class="info-row">
                <view class="info-item">
                  <text class="label">产地：</text>
                  <text class="value">{{ item.originPlace || '未填写' }}</text>
                </view>
              </view>
            </view>

            <view v-if="item.inspectionStatus === '0'" class="item-footer">
              <view class="action-btn primary-btn" @click.stop="showTestDialog(item)">
                <uni-icons type="compose" size="16" color="#fff"></uni-icons>
                <text>录入检测结果</text>
              </view>
            </view>
            <view v-else class="item-footer">
              <view class="test-result">
                <view class="result-info">
                  <uni-icons :type="item.inspectionStatus === '1' ? 'checkbox-filled' : 'closeempty'" 
                    size="16" :color="item.inspectionStatus === '1' ? '#52c41a' : '#ff4d4f'"></uni-icons>
                  <text>{{ item.inspectionStatus === '1' ? '检测合格' : '检测不合格' }}</text>
                </view>
                <text class="test-time">{{ formatTime(item.inspectionTime) }}</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view v-else-if="!loading" class="empty-state">
          <uni-icons type="info" size="60" color="#ccc"></uni-icons>
          <text class="empty-text">{{ currentTab === '0' ? '暂无待检测项目' : '暂无检测记录' }}</text>
        </view>

        <!-- 加载更多 -->
        <view v-if="loading && list.length > 0" class="loading-more">
          <uni-load-more status="loading"></uni-load-more>
        </view>
      </scroll-view>
    </view>

    <!-- 检测录入弹窗 -->
    <uni-popup ref="testPopup" type="bottom" background-color="#fff">
      <view class="test-popup">
        <view class="popup-header">
          <text class="popup-title">录入检测结果</text>
          <uni-icons type="close" size="24" color="#999" @click="closeTestDialog"></uni-icons>
        </view>
        
        <scroll-view scroll-y class="popup-content">
          <!-- 商品信息 -->
          <view class="info-section">
            <view class="section-title">商品信息</view>
            <view class="info-list">
              <view class="info-item">
                <text class="label">商品名称</text>
                <text class="value">{{ currentItem.goodsName }}</text>
              </view>
              <view class="info-item">
                <text class="label">商户名称</text>
                <text class="value">{{ currentItem.merchantName }}</text>
              </view>
              <view class="info-item">
                <text class="label">供货商</text>
                <text class="value">{{ currentItem.supplierName }}</text>
              </view>
              <view class="info-item">
                <text class="label">数量</text>
                <text class="value">{{ currentItem.quantity }}{{ currentItem.unit }}</text>
              </view>
            </view>
          </view>

          <!-- 检测项目 -->
          <view class="test-section">
            <view class="section-title">检测项目</view>
            <view class="test-items">
              <view v-for="(item, index) in testItems" :key="index" 
                :class="['test-item-option', testForm.testItems.includes(item.value) ? 'selected' : '']"
                @click="toggleTestItem(item.value)">
                <uni-icons :type="testForm.testItems.includes(item.value) ? 'checkbox-filled' : 'checkbox'" 
                  size="18" :color="testForm.testItems.includes(item.value) ? '#1890ff' : '#999'"></uni-icons>
                <text>{{ item.label }}</text>
              </view>
            </view>
          </view>

          <!-- 检测结果 -->
          <view class="result-section">
            <view class="section-title">检测结果</view>
            <view class="result-options">
              <view 
                :class="['result-option', testForm.result === '1' ? 'selected pass' : '']"
                @click="testForm.result = '1'">
                <uni-icons type="checkbox-filled" size="20" 
                  :color="testForm.result === '1' ? '#52c41a' : '#999'"></uni-icons>
                <text>合格</text>
              </view>
              <view 
                :class="['result-option', testForm.result === '2' ? 'selected fail' : '']"
                @click="testForm.result = '2'">
                <uni-icons type="closeempty" size="20" 
                  :color="testForm.result === '2' ? '#ff4d4f' : '#999'"></uni-icons>
                <text>不合格</text>
              </view>
            </view>
          </view>

          <!-- 不合格原因 -->
          <view v-if="testForm.result === '2'" class="reason-section">
            <view class="section-title">不合格原因</view>
            <view class="reason-input">
              <textarea 
                v-model="testForm.reason" 
                placeholder="请输入不合格原因，如：农药残留超标、重金属超标等"
                maxlength="200"
              ></textarea>
              <text class="char-count">{{ testForm.reason.length }}/200</text>
            </view>
          </view>

          <!-- 备注 -->
          <view class="remark-section">
            <view class="section-title">备注（选填）</view>
            <textarea 
              v-model="testForm.remark" 
              placeholder="请输入备注信息"
              maxlength="500"
            ></textarea>
          </view>
        </scroll-view>

        <view class="popup-footer">
          <button class="btn-cancel" @click="closeTestDialog">取消</button>
          <button class="btn-confirm" @click="submitTest">提交结果</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { listAppointmentDetails, submitInspection } from '@/api/business/appointment.js'

export default {
  data() {
    return {
      currentTab: '0',
      list: [],
      loading: false,
      refreshing: false,
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      statistics: {
        today: 0,
        passed: 0,
        failed: 0
      },
      currentItem: {},
      testForm: {
        testItems: [],
        result: '',
        reason: '',
        remark: ''
      },
      testItems: [
        { label: '农药残留', value: 'pesticide' },
        { label: '重金属', value: 'heavy_metal' },
        { label: '添加剂', value: 'additive' },
        { label: '微生物', value: 'microbe' },
        { label: '瘦肉精', value: 'clenbuterol' },
        { label: '其他', value: 'other' }
      ]
    }
  },
  onLoad() {
    this.loadStatistics()
    this.loadList(true)
  },
  methods: {
    // 加载统计数据
    async loadStatistics() {
      try {
        // 获取今日待检测数量
        const pendingRes = await listAppointmentDetails({
          needInspection: '1',
          inspectionStatus: '0',
          pageNum: 1,
          pageSize: 1
        })
        
        // 获取今日已通过数量
        const passedRes = await listAppointmentDetails({
          needInspection: '1',
          inspectionStatus: '1',
          pageNum: 1,
          pageSize: 1
        })
        
        // 获取今日不合格数量
        const failedRes = await listAppointmentDetails({
          needInspection: '1',
          inspectionStatus: '2',
          pageNum: 1,
          pageSize: 1
        })
        
        this.statistics = {
          today: (pendingRes.total || 0) + (passedRes.total || 0) + (failedRes.total || 0),
          passed: passedRes.total || 0,
          failed: failedRes.total || 0
        }
      } catch (error) {
        console.error('加载统计数据失败:', error)
        // 如果失败，使用默认值
        this.statistics = {
          today: 0,
          passed: 0,
          failed: 0
        }
      }
    },
    
    // 加载列表
    async loadList(refresh = false) {
      if (this.loading) return
      if (!refresh && !this.hasMore) return
      
      this.loading = true
      if (refresh) {
        this.pageNum = 1
        this.hasMore = true
      }
      
      try {
        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          needInspection: '1'
        }
        
        // 根据标签筛选
        if (this.currentTab === '0') {
          params.inspectionStatus = '0'
        } else {
          params.inspectionStatus = '1,2'
        }
        
        const res = await listAppointmentDetails(params)
        
        if (res.code === 200) {
          const data = res.rows || []
          const total = res.total || 0
          
          if (refresh) {
            this.list = data
          } else {
            this.list = [...this.list, ...data]
          }
          
          this.hasMore = this.list.length < total
          if (this.hasMore) {
            this.pageNum++
          }
        } else {
          if (refresh) {
            this.list = []
          }
          this.hasMore = false
        }
      } catch (error) {
        console.error('加载列表失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
        if (refresh) {
          this.list = []
        }
        this.hasMore = false
      } finally {
        this.loading = false
        this.refreshing = false
      }
    },
    
    // 切换标签
    switchTab(tab) {
      this.currentTab = tab
      this.loadList(true)
    },
    
    // 下拉刷新
    onRefresh() {
      this.refreshing = true
      this.loadStatistics()
      this.loadList(true)
    },
    
    // 加载更多
    loadMore() {
      this.loadList()
    },
    
    // 显示检测弹窗
    showTestDialog(item) {
      if (item.inspectionStatus !== '0') {
        // 已检测的只查看详情
        uni.navigateTo({
          url: `/pages/check/detail?applyId=${item.applyId}&detailId=${item.detailId}`
        })
        return
      }
      
      this.currentItem = item
      this.testForm = {
        testItems: [],
        result: '',
        reason: '',
        remark: ''
      }
      this.$refs.testPopup.open()
    },
    
    // 关闭弹窗
    closeTestDialog() {
      this.$refs.testPopup.close()
    },
    
    // 切换检测项目
    toggleTestItem(value) {
      const index = this.testForm.testItems.indexOf(value)
      if (index > -1) {
        this.testForm.testItems.splice(index, 1)
      } else {
        this.testForm.testItems.push(value)
      }
    },
    
    // 提交检测结果
    async submitTest() {
      if (this.testForm.testItems.length === 0) {
        uni.showToast({
          title: '请选择检测项目',
          icon: 'none'
        })
        return
      }
      
      if (!this.testForm.result) {
        uni.showToast({
          title: '请选择检测结果',
          icon: 'none'
        })
        return
      }
      
      if (this.testForm.result === '2' && !this.testForm.reason) {
        uni.showToast({
          title: '请输入不合格原因',
          icon: 'none'
        })
        return
      }
      
      uni.showLoading({
        title: '提交中...'
      })
      
      try {
        const data = {
          detailId: this.currentItem.detailId,
          inspectionStatus: this.testForm.result,
          inspectionItems: this.testForm.testItems.join(','),
          inspectionReason: this.testForm.reason,
          remark: this.testForm.remark
        }
        
        const res = await submitInspection(data)
        
        if (res.code === 200) {
          uni.showToast({
            title: '提交成功',
            icon: 'success'
          })
          
          this.closeTestDialog()
          this.loadStatistics()
          this.loadList(true)
        } else {
          uni.showToast({
            title: res.msg || '提交失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('提交失败:', error)
        uni.showToast({
          title: '提交失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      return time.replace('T', ' ').substring(0, 16)
    }
  }
}
</script>

<style scoped>
.quicktest-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 统计卡片 */
.stat-cards {
  display: flex;
  padding: 20rpx;
  gap: 20rpx;
}

.stat-card {
  flex: 1;
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  display: flex;
  align-items: center;
  gap: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.stat-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-icon.blue {
  background: rgba(24, 144, 255, 0.1);
}

.stat-icon.green {
  background: rgba(82, 196, 26, 0.1);
}

.stat-icon.red {
  background: rgba(255, 77, 79, 0.1);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 4rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #999;
}

/* 区块样式 */
.section {
  background: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

/* 标签切换 */
.filter-tabs {
  display: flex;
  gap: 20rpx;
}

.tab-item {
  padding: 8rpx 24rpx;
  font-size: 26rpx;
  color: #666;
  background: #f5f7fa;
  border-radius: 20rpx;
  transition: all 0.3s;
}

.tab-item.active {
  background: linear-gradient(135deg, #1890ff, #40a9ff);
  color: #fff;
}

/* 列表 */
.list-container {
  height: calc(100vh - 320rpx);
}

.test-item {
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
}

.goods-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.merchant-info {
  font-size: 24rpx;
  color: #666;
}

.status-badge {
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: 500;
}

.status-badge.pending {
  background: #fffbe6;
  color: #faad14;
}

.status-badge.passed {
  background: #f6ffed;
  color: #52c41a;
}

.status-badge.failed {
  background: #fff1f0;
  color: #ff4d4f;
}

.item-content {
  padding: 20rpx 0;
  border-top: 1rpx solid #e8e8e8;
  border-bottom: 1rpx solid #e8e8e8;
}

.info-row {
  display: flex;
  margin-bottom: 12rpx;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-item {
  flex: 1;
  display: flex;
  font-size: 26rpx;
}

.info-item .label {
  color: #999;
  margin-right: 8rpx;
}

.info-item .value {
  color: #333;
  flex: 1;
}

.item-footer {
  margin-top: 20rpx;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  padding: 16rpx 0;
  border-radius: 12rpx;
  font-size: 28rpx;
  font-weight: 500;
}

.primary-btn {
  background: linear-gradient(135deg, #1890ff, #40a9ff);
  color: #fff;
}

.test-result {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-info {
  display: flex;
  align-items: center;
  gap: 8rpx;
  font-size: 26rpx;
  color: #666;
}

.test-time {
  font-size: 24rpx;
  color: #999;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-text {
  color: #999;
  font-size: 28rpx;
  margin-top: 30rpx;
}

/* 弹窗样式 */
.test-popup {
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.popup-content {
  flex: 1;
  padding: 30rpx;
  max-height: 60vh;
}

.info-section,
.test-section,
.result-section,
.reason-section,
.remark-section {
  margin-bottom: 40rpx;
}

.info-list {
  margin-top: 20rpx;
}

.info-list .info-item {
  display: flex;
  padding: 12rpx 0;
  font-size: 28rpx;
}

.info-list .label {
  width: 150rpx;
  color: #999;
}

.info-list .value {
  flex: 1;
  color: #333;
}

/* 检测项目 */
.test-items {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-top: 20rpx;
}

.test-item-option {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 24rpx;
  background: #f5f7fa;
  border-radius: 12rpx;
  font-size: 26rpx;
  color: #666;
  transition: all 0.3s;
}

.test-item-option.selected {
  background: #e6f7ff;
  color: #1890ff;
  border: 1rpx solid #91d5ff;
}

/* 检测结果 */
.result-options {
  display: flex;
  gap: 30rpx;
  margin-top: 20rpx;
}

.result-option {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  padding: 24rpx;
  background: #f5f7fa;
  border-radius: 12rpx;
  font-size: 30rpx;
  color: #666;
  transition: all 0.3s;
}

.result-option.selected.pass {
  background: #f6ffed;
  color: #52c41a;
  border: 1rpx solid #b7eb8f;
}

.result-option.selected.fail {
  background: #fff1f0;
  color: #ff4d4f;
  border: 1rpx solid #ffccc7;
}

/* 不合格原因 */
.reason-input {
  position: relative;
  margin-top: 20rpx;
}

.reason-input textarea {
  width: 100%;
  min-height: 150rpx;
  padding: 20rpx;
  background: #f5f7fa;
  border-radius: 12rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.char-count {
  position: absolute;
  right: 20rpx;
  bottom: 20rpx;
  font-size: 24rpx;
  color: #999;
}

/* 备注 */
.remark-section textarea {
  width: 100%;
  min-height: 150rpx;
  padding: 20rpx;
  background: #f5f7fa;
  border-radius: 12rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  margin-top: 20rpx;
}

/* 底部按钮 */
.popup-footer {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
  border-top: 1rpx solid #f0f0f0;
}

.btn-cancel,
.btn-confirm {
  flex: 1;
  height: 90rpx;
  border-radius: 20rpx;
  font-size: 30rpx;
  font-weight: 500;
  border: none;
}

.btn-cancel {
  background: #f5f7fa;
  color: #666;
}

.btn-confirm {
  background: linear-gradient(135deg, #1890ff, #40a9ff);
  color: #fff;
}

.loading-more {
  padding: 30rpx;
  text-align: center;
}
</style>